<template>

  <el-table :data="tableData" style="width: 100%">
    <el-table-column prop="id" label="奖品id" width="150"/>
    <el-table-column prop="name" label="奖品" width="120"/>
    <el-table-column label="图片" width="120" #default="scope">
      <img :src="scope.row.pictureUrl" width="50" height="50">
    </el-table-column>
    <el-table-column prop="createdTime" label="创建时间" width="120"/>
    <el-table-column prop="description" label="描述" width="120"/>
    <el-table-column fixed="right" label="Operations" min-width="120">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="toupdate(scope.row)">
          修改
        </el-button>
      </template>
    </el-table-column>
  </el-table>


  <el-dialog
      v-model="dialogVisible1"
      title="新增"
      width="500"
      :before-close="handleClose"
  >
    <el-form :model="gift" label-width="auto" style="max-width: 600px">
      <el-form-item label="奖品id">
        <el-input v-model="gift.id"/>
      </el-form-item>
      <el-form-item label="奖品名称">
        <el-input v-model="gift.name"/>
      </el-form-item>
      <el-form-item label="奖品图片">
        <!--   图片上传     -->
        <van-uploader
            :v-model="gift.pictureUrl"
            :max-count="1"
            :before-read="beforeRead1"
            :after-read="afterRead1"
        >
        <el-image style="width: 100px; height: 100px" :src="gift.pictureUrl" :fit="fit" />
      </van-uploader>
      </el-form-item>
      <el-form-item label="比重">
        <el-input v-model="gift.remark"/>
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="gift.description"/>
      </el-form-item>
      <el-form-item label="数量">
        <el-input v-model="gift.number"/>
      </el-form-item>
      <el-button @click="UpdateGift()">修改</el-button>
    </el-form>
  </el-dialog>
</template>


<script setup>
import {ref} from "vue";
import {getGifts, uploadImage ,saveGift ,updateGift ,deleteGift} from "@/api/staff.js";
import { showToast } from 'vant';
import {ElMessage} from "element-plus";

const tableData = ref([]);
const dialogVisible = ref(false);
const form = ref({
  name: '',
  pictureUrl: '', // 新增，用于存储图片地址
  remark:'',
  description: '',
});

// 获取奖品列表数据的函数
GetGifts();

function GetGifts() {
  getGifts().then(res => {
    if (res.data.code == 200000) {
      tableData.value = res.data.data;
      console.log(tableData.value)
    }
  });
}

const fileList = ref([]);

// 上传前置检查
const beforeRead = (file) => {
  // 文件类型检查
  if (!['image/jpeg', 'image/png'].includes(file.type)) {
    showToast('请上传 jpg/png 格式图片');
    return false;
  }
  // 文件大小限制（2MB）
  if (file.size > 2 * 1024 * 1024) {
    showToast('文件大小不能超过 2M');
    return false;
  }
  return true;
};

// 上传后的处理
const afterRead = async (file) => {
  // 创建 FormData
  const formData = new FormData();
  formData.append('file', file.file);
  console.log(file)
  try {
    const response = await uploadImage(formData);
    if (response.data.code === 200000) {
      console.log(response)
      form.value.pictureUrl = response.data.data; // 根据实际返回数据结构调整
      showToast('上传成功');
    } else {
      showToast('上传失败');
    }
  } catch (error) {
    console.error('上传错误:', error);
    showToast('上传失败');
  }
};

function AddGift(){
  saveGift(form.value).then(res =>{
    if(res.data.code == 200000){
      dialogVisible.value = false;
      GetGifts()
      ElMessage({
        message: res.data.msg,
        type: 'success'
      });
    }else {
      ElMessage({
        message: res.data.msg,
        type: 'error'
      });
    }
  })
}


const dialogVisible1 = ref(false)
const gift = ref({
  id:'',
  name: '',
  pictureUrl: '', // 新增，用于存储图片地址
  remark:'',
  description: '',
  number:''
});

function toupdate(data){
  gift.value = data
  dialogVisible1.value = true
}
// 上传前置检查
const beforeRead1 = (file) => {
  // 文件类型检查
  if (!['image/jpeg', 'image/png'].includes(file.type)) {
    showToast('请上传 jpg/png 格式图片');
    return false;
  }
  // 文件大小限制（2MB）
  if (file.size > 2 * 1024 * 1024) {
    showToast('文件大小不能超过 2M');
    return false;
  }
  return true;
};

// 上传后的处理
const afterRead1 = async (file) => {
  // 创建 FormData
  const formData = new FormData();
  formData.append('file', file.file);
  console.log(file)
  try {
    const response = await uploadImage(formData);
    if (response.data.code === 200000) {
      console.log(response)
      gift.value.pictureUrl = response.data.data; // 根据实际返回数据结构调整
      showToast('上传成功');
    } else {
      showToast('上传失败');
    }
  } catch (error) {
    console.error('上传错误:', error);
    showToast('上传失败');
  }
};

function UpdateGift(){
  updateGift(gift.value).then(res => {
    if(res.data.code==200000){
      dialogVisible1.value = false;
      GetGifts()
      ElMessage({
        message: res.data.msg,
        type: 'success'
      });
    }
  })
}

function DeleteGift(data){
  deleteGift(data).then(res => {
    if(res.data.code==200000){
      GetGifts()
      ElMessage({
        message: res.data.msg,
        type: 'success'
      });
    }
  })
}
</script>


<style scoped>


.avatar-uploader.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader.el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader.el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
<style>
/* 可以添加一些自定义样式 */
:deep(.van-uploader) {
  --van-uploader-size: 178px;
}

:deep(.van-uploader__upload) {
  background-color: #fff;
  border: 1px dashed #d9d9d9;
}

:deep(.van-uploader__upload:hover) {
  border-color: var(--el-color-primary);
}
</style>
